<template>
	<view class="">
		<tn-nav-bar fixed :bottomShadow="false" :isBack="false" customBack :height="68" backgroundColor="#fe1313">
			<view class="tn-flex tn-flex-row-between tn-padding-right-sm tn-padding-left-sm"
				style="width: 750rpx;color: #fff;">
				<view class="tn-flex-1 tn-flex tn-flex-col-center tn-text-lg">
					<text class='tn-icon tn-icon-location-fill'></text>
					<text>{{province}}</text>
				</view>
				<text class="tn-flex-1 tn-text-center tn-text-lg">集采社</text>
				<view class="tn-flex-1"></view>
			</view>
		</tn-nav-bar>
		<view class="content tn-flex tn-flex-direction-column" :style="{'marginTop': vuex_custom_bar_height + 'rpx'}">
			<view class="header" :style="{'paddingTop': vuex_custom_bar_height + 'rpx'}">
				<view
					class="headerList tn-flex tn-flex-row-between tn-flex-col-center tn-padding-left-sm tn-padding-right-sm tn-margin-bottom-xs">
					<view class="headerLift tn-flex tn-flex-col-center">
						<tn-avatar :src="user.avatarUrl" size="lg"></tn-avatar>
						<view
							class="headerText tn-flex tn-flex-direction-column tn-margin-left-sm tn-margin-right-sm tn-text-lg"
							style="color: #fff;">
							<text>{{user.phone||'用户未登录'}}</text>
							<text>{{newDate}}</text>
						</view>
					</view>
					<view class="">
						<tn-button shape="round" fontColor="#ff1313" @click="toMerchantApplication">
							<text>集采商家</text>
						</tn-button>
					</view>
				</view>
			</view>
			<view class="tn-padding-right-sm tn-padding-left-sm tn-padding-bottom-sm" style="margin-top: -120rpx;">
				<tn-swiper :list="imgList" @click="toUrl"></tn-swiper>
			</view>
			<view class="tags tn-padding-left-sm tn-padding-right-sm">
				<tn-subsection :list="['附近集采', '我的参与', '我的发布']" :borderRadius="50" backgroundColor="#eaeaea"
					buttonColor="#ff1313" inactiveColor="#ff1313" @change="tagsChange"></tn-subsection>
			</view>
			<view
				class="classify tn-padding-left-sm tn-padding-right-sm tn-flex tn-flex-col-center tn-margin-bottom-xs tn-margin-top-xs">
				<view class="tn-flex-1">
					<tn-subsection v-if="subselist.length>1" :list="subselist" mode="button" backgroundColor="#fff"
						buttonColor="#E83A30" width="100rpx" inactiveColor="#3d3d3d" animationType="cubic-bezier"
						@change="classifyChange">
					</tn-subsection>
				</view>
				<view class="tn-flex tn-flex-row-center tn-flex-col-center" style="width: 120rpx;">
					<view v-if="tagIndex==0" class="tn-flex tn-flex-row-center tn-flex-col-center"
						style="width: 100rpx;height: 40rpx;background-color: #d8d8d8;color: #636363;border-radius: 10rpx;"
						@click="selectShow=true">
						<text>{{distanceNum}}km</text>
						<text class="tn-icon-down-triangle"></text>
					</view>
				</view>
			</view>
			<view class="contentList tn-flex-1">
				<view
					class="listItem tn-padding-left-sm tn-padding-right-sm tn-flex tn-flex-row-between tn-flex-col-center"
					v-for="(v,i) in contentList" :key="v.id" @click="goTo(v)">
					<view class="tn-flex tn-flex-direction-column tn-flex-row-center">
						<text class="tn-text-xl tn-margin-bottom-xs tn-text-ellipsis">{{v.title}}</text>
						<text class="tn-text-md">【{{v.count}}条留言】{{v.list[0].content||'暂无留言'}}</text>
					</view>
					<view class="tn-flex tn-flex-direction-column tn-flex-row-center tn-flex-col-center">
						<text class="tn-text-xl tn-margin-bottom-xs">{{v.canyu}}</text>
						<text class="tn-text-md tn-text-ellipsis">{{v.create_at}}</text>
					</view>
				</view>
			</view>
		</view>
		<tn-button shape="round" backgroundColor="#ff1313" fontSize="32" width="350rpx" height="80rpx"
			fontColor="tn-color-white" class="btn" @click="toInitiateSolitaire">发起集采招标
		</tn-button>
		<view style="padding-bottom: 88rpx;"></view>
		<view class="tn-padding-bottom-lg"></view>
		<tn-modal v-model="scopeShow" :custom="true">
			<view class="custom-modal-content tn-flex tn-flex-direction-column" style="height: 200rpx;">
				<view class="tn-flex-2 tn-flex tn-flex-row-center tn-flex-col-center">
					此小程序将获取你的手机号
				</view>
				<view class="tn-flex-1 tn-flex tn-flex-row-between tn-flex-col-center">
					<button @click="scopeShow=false" class="tn-flex-1" style="background-color: #fff;">取消</button>
					<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" class="tn-flex-1"
						style="background-color: #fff;">确认</button>
				</view>
			</view>
		</tn-modal>
		<tn-select v-model="selectShow" mode="single" :list="selectList" @confirm="selectChange"></tn-select>
	</view>
</template>

<script>
	import {
		jicaiTypeApi,
		jicaiListApi,
		resphoneApi,
		addUserApi,
		userinfoApi,
		bannerListApi
	} from '../../apis/indexApi.js'
	import {
		useNewDate
	} from '../../utlis/hook.js'
	// import {
	// 	httpURL
	// } from '../../utlis/http.js'
	export default {
		data() {
			return {
				address: '',
				province: '',
				user: {
					name: '',
					avatarUrl: ''
				},
				newDate: '',
				imgList: [{
						image: 'https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF',
						title: 'xxx'
					},
					{
						image: 'https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF',
						title: 'xxx'
					},
				],
				subselist: ['全部'],
				subseData: [],
				loginResCode: '',
				tagIndex: 0,
				classifyIndex: 0,
				selectShow: false,
				distanceNum: 1,
				selectList: [{
					label: '1km',
					value: 1
				}, {
					label: '3km',
					value: 3
				}],
				scopeShow: false,
				contentList: [],
				isDenlu: 0
			}
		},
		onLoad() {
			let thsi = this;
			jicaiTypeApi().then(res => {
				if (res.data.msg == '成功') {

					res.data.data.forEach(v => {
						thsi.subselist.push(v.name);
					})
					thsi.subseData = res.data.data;
				}
			}).catch(err => {
				console.log(err)
			})
			// console.log('获取appid')
			const accountInfo = uni.getAccountInfoSync();
			// console.log("微信端appid :", accountInfo.miniProgram.appId); // 小程序 appId
			this.appID = accountInfo.miniProgram.appId;
			// let thsi = this;

			// console.log(111111)
			uni.login({
				provider: 'weixin',
				success: (loginRes) => {
					if (loginRes.errMsg == 'login:ok') {
						thsi.loginResCode = loginRes.code;
					}
				}
			});
			if (!uni.getStorageSync('user').openid) {
				this.scopeShow = true;
			}
			this.getAddressScope();
		},
		onShow() {
			this.newDate = useNewDate();
			uni.getStorageSync('user').phone && (this.user.phone = uni.getStorageSync('user').phone);
			this.user.avatarUrl = 'https://image.580ck.com/jicai/touxian.png';
			if (uni.getStorageSync('user').u_id && uni.getStorageSync('user').longitude) {
				this.render({});
			}
		},
		watch: {
			isDenlu() {
				if (this.isDenlu % 2 == 0) {
					this.addUserFun();
				}
				if (this.isDenlu % 3 == 0) {
					this.render({});
				}
			},
			distanceNum() {
				this.render({});
			},
			province() {
				let thsi = this;
				let user = uni.getStorageSync('user') || {};
				user.province = thsi.province;
				uni.setStorageSync('user', user);
				bannerListApi(thsi.province).then(res => {
					if (res.data.msg == '成功') {
						let _img = res.data.data;
						_img = _img.filter(v => v.type === 1);
						_img = _img.map(v => v.image = 'http://admin.xiaobiaohui.com/' + v.image)
						this.imgList = _img
						// console.log(_img)
					}
				}).catch(err => {
					console.log(err)
				})
			}
		},
		methods: {
			render(obj) {
				let _data = {
					type: obj['type'] || this.classifyIndex != 0 ? this.subseData[(this.classifyIndex == 0 ? 1 :
						this.classifyIndex) - 1].id : 0,
					u_id: uni.getStorageSync('user').u_id,
					longitude: uni.getStorageSync('user').longitude.toFixed(5) || this.getAddressScope(),
					latitude: uni.getStorageSync('user').latitude.toFixed(5) || this.getAddressScope(),
					gongli: obj['gongli'] || this.distanceNum,
					toptype: obj['toptype'] || this.tagIndex
				}
				jicaiListApi(_data).then(res => {
					// console.log(res)
					if (res.data.msg == '成功') {
						this.contentList = res.data.data;
					} else {
						this.contentList = [];
					}
				}).catch(err => {
					console.log(err)
				})
			},
			toUrl(e) {
				console.log(e)
			},
			tagsChange(obj) {
				this.tagIndex = obj.index;
				let _data = {
					toptype: obj.index
				}
				console.log(this.classifyIndex)
				this.render(_data);
			},
			classifyChange(obj) {
				this.classifyIndex = obj.index;
				let _data = {
					type: 0
				}
				if (obj.index == 0) {
					_data.type = 0;
				} else {
					_data.type = this.subseData[obj.index - 1].id;
				}
				this.render(_data);
			},
			getAddressScope() {
				let _this = this;
				uni.getSetting({
					success(res) {
						if (!res.authSetting['scope.userLocation']) {
							// 未授权
							uni.authorize({
								scope: 'scope.userLocation',
								success() { //1.1 允许授权
									_this.getAddress();
								},
								fail() { //1.2 拒绝授权
									console.log("你拒绝了授权，无法获得周边信息")
								}
							})
						} else {
							_this.getAddress();
						}
					}
				});
			},
			getPhoneNumber(ev) {
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				let that = this;
				if (ev.detail.errMsg == 'getPhoneNumber:fail user deny') {
					console.log('用户拒绝提供手机号');
				} else {
					// console.log('用户同意提供手机号');
					// console.log("iv", ev.detail.iv)
					// console.log("encryptedData", ev.detail.encryptedData)
					let encryptedData = ev.detail.encryptedData
					let iv = ev.detail.iv

					//检查登录
					uni.checkSession({
						success: (res) => {
							console.log("checkSession--success---res", res)
							if (res.errMsg == 'checkSession:ok') {
								console.log(res);
								console.log('登录暂未过期');
								if (encryptedData !== undefined && iv !== undefined) {
									that.getPhone(that.loginResCode, encryptedData, iv)
								}
							}
						},
						fail: (res) => {
							// console.log("checkSession---fail---res", res)
							console.log('登录已过期');
							//再执行一次login
							uni.login({
								provider: 'weixin',
								success: function(loginRes) {
									// console.log("loginRes.code", loginRes.code);
									that.loginResCode = loginRes.code;

									if (encryptedData !== undefined && iv !== undefined) {
										that.getPhone(that.loginResCode, encryptedData, iv)
									}
								}
							});
						}
					})
				}
			},
			addUserFun() {
				if (!uni.getStorageSync('user').openid) {
					this.addUserFun();
					return
				}
				// if (!uni.getStorageSync('user').name) {
				// 	this.addUserFun();
				// 	return
				// }
				addUserApi({
					phone: uni.getStorageSync('user').phone,
					openid: uni.getStorageSync('user').openid
					// nickname: uni.getStorageSync('user').name,
					// nickimage: uni.getStorageSync('user').avatarUrl
				}).then(results => {
					if (results.data.msg == '添加成功') {
						// console.log(results)
						const user = uni.getStorageSync('user') || {};
						user.u_id = results.data.u_id;
						// user.openid = res.data.openid;
						// user.phone = res.data.data.phoneNumber;
						// user.appid = res.data.data.watermark.appid;
						// user.userType = results.data.type;
						uni.setStorageSync('user', user);
						uni.hideLoading();
						this.scopeShow = false;
						this.isDenlu++;
					}
				}).catch(err => {
					console.log(err)
				})
			},
			getPhone(code, encryptedData, iv) {
				resphoneApi({
					code,
					encryptedData,
					iv
				}).then(res => {
					// console.log(res)
					if (res.data.code == 200) {
						// addUserApi({
						// 	phone: res.data.data.phoneNumber,
						// 	openid: res.data.openid,
						// 	nickname: uni.getStorageSync('user').name,
						// 	nickimage: uni.getStorageSync('user').avatarUrl
						// }).then(results => {
						// 	if (results.data.msg == '添加成功') {
						// 		// console.log(results)
						// 		const user = uni.getStorageSync('user') || {};
						// 		user.u_id = results.data.u_id;
						// 		user.openid = res.data.openid;
						// 		user.phone = res.data.data.phoneNumber;
						// 		user.appid = res.data.data.watermark.appid;
						// 		// user.userType = results.data.type;
						// 		uni.setStorageSync('user', user);
						// 		uni.hideLoading();
						// 		this.scopeShow = false;
						// 		this.isDenlu++;
						// 	}
						// }).catch(err => {
						// 	console.log(err)
						// })
						const user = uni.getStorageSync('user') || {};
						user.openid = res.data.openid;
						user.phone = res.data.data.phoneNumber;
						user.appid = res.data.data.watermark.appid;
						uni.setStorageSync('user', user);
						this.user.phone = res.data.data.phoneNumber;
						uni.hideLoading();
						this.scopeShow = false;
						this.isDenlu++;
					} else {
						console.log('获取解密后的手机号失败', res.data.obj)
						uni.showToast({
							title: '获取手机失败，请重试',
							icon: 'none',
							duration: 1500,
						})
					}
				}).catch(err => {
					console.log(err)
				})

			},
			getAddress() {
				let _this = this;
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				console.log('正在获取地址')
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: (res) => {
						// console.log('当前位置的经度：' + res.longitude);
						// console.log('当前位置的纬度：' + res.latitude);
						let user = uni.getStorageSync('user') || {};
						user.longitude = res.longitude;
						user.latitude = res.latitude;
						uni.setStorageSync('user', user);
						console.log('已获取经纬度', res.longitude, res.latitude)
						uni.request({
							header: {
								"Content-Type": "application/text"
							},
							url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=' +
								res.latitude + ',' + res.longitude +
								'&key=DSJBZ-SGIEP-S5RDM-LNEZN-LTRH3-MRBA4',
							success(re) {
								console.log('正在转换地址')
								if (re.statusCode === 200) {
									_this.address = re.data.result.address;
									uni.setStorageSync('address', re.data.result.address);
									_this.province = re.data.result.address.slice(re.data.result
										.address.indexOf('省') + 1,
										re.data.result.address.indexOf('市') + 1);
									_this.isDenlu++;
								} else {
									_this.$t.message.toast("获取位置失败")
								}
								uni.hideLoading();
							},
							fail(err) {
								console.log('获取地址失败', err)
							}
						});
					},
					fail(err) {
						console.log('getLocation获取地址失败', err)
					}
				});
			},
			selectChange(v) {
				// console.log(v);
				this.distanceNum = v[0].value;
			},
			// getLogin(fun) {
			// 	// uni.showLoading({
			// 	// 	title: '加载中'
			// 	// });
			// 	let _this = this;
			// 	uni.getUserProfile({
			// 		desc: '1312312',
			// 		success: res => {
			// 			console.log('头像，昵称', res)
			// 			_this.user.name = res.userInfo.nickName;
			// 			_this.user.avatarUrl = res.userInfo.avatarUrl;
			// 			let user = uni.getStorageSync('user') || {};
			// 			user.name = res.userInfo.nickName;
			// 			user.avatarUrl = res.userInfo.avatarUrl;
			// 			uni.setStorageSync('user', user);
			// 			// uni.hideLoading();
			// 			// fun && fun();
			// 		},
			// 		fail: res => {
			// 			//拒绝授权
			// 			// uni.hideLoading();
			// 			return;
			// 		}
			// 	});
			// },
			goTo(v) {
				// let _this = this;
				// if (!uni.getStorageSync('user').name) {
				// 	this.getLogin(_this.toPage);
				// } else {
				// 	this.toPage();
				// }
				this.toPage(v);
			},
			toPage(v) {
				console.log(v)
				switch (this.tagIndex) {
					case 0:
						uni.navigateTo({
							url: `/pages/participate/participate?id=${v.id}`
						});
						break;
					case 1:
						uni.navigateTo({
							url: `/pages/collectinformation/collectinformation?type=${this.tagIndex}&id=${v.id}`
						});
						break;
					case 2:
						uni.navigateTo({
							url: `/pages/collectinformation/collectinformation?type=${this.tagIndex}&id=${v.id}`
						});
						break;
				}
			},
			toInitiateSolitaire() {
				uni.navigateTo({
					url: '/pages/initiateSolitaire/initiateSolitaire'
				});
			},
			toMerchantApplication() {
				userinfoApi(uni.getStorageSync('user').u_id).then(res => {
					if (res.data.msg == '成功') {
						let user = uni.getStorageSync('user') || {};
						user.longitudeMerchant = res.data.data.longitude;
						user.latitudeMerchant = res.data.data.latitude;
						uni.setStorageSync('user', user);
						switch (res.data.data.type) {
							case 1:
								uni.navigateTo({
									url: '/pages/MerchantApplication/MerchantApplication?type=0'
								});
								break;
							case 2:
								uni.navigateTo({
									url: '/pages/MerchantApplication/MerchantApplication?type=0&userType=2'
								});
								break;
							case 3:
								uni.navigateTo({
									url: '/pages/CentralizedProcurementBiddingInformation/CentralizedProcurementBiddingInformation'
								});
								break;
						}
					}
				}).catch(err => {
					console.log(err)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		width: 750rpx;

		.header {
			width: 100%;
			height: 320rpx;
			background-color: #fe1313;

			.headerList {
				height: 150rpx;
				width: 100%;
			}
		}


		.contentList {
			width: 100%;
			overflow-y: scroll;

			.listItem {
				width: 100%;
				height: 140rpx;
				border-top: 1px solid #b8b6b6;
				border-bottom: 1px solid #b8b6b6;
				background-color: #f9f9f9;

			}
		}


	}

	.btn {
		position: fixed;
		bottom: 40rpx;
		left: 50%;
		transform: translateX(-50%);
	}
</style>
